#include "MemoryPool.h"

namespace RTRT {
	
	MemoryPool::MemoryPool() 
	{
		m_nodePool = (char*)(new KDTreeNode[MAX_POOL_SIZE]);
		m_triPtrPool = (char*)(new TriangleList[TRIANGLE_PTR_POOL_SIZE]);
		
		unsigned long addr = (unsigned long)m_nodePool;
		m_kdNodePtr = (KDTreeNode*) ((addr + 32) & (0xffffffff - 31));
		
		addr = (unsigned long)m_triPtrPool;
		m_triListPtr = (TriangleList*) ((addr + 32) & (0xffffffff - 31));
		TriangleList *ptr = m_triPtr;
		
		// Link the list
		for (int i=0; i < 99995; i++)
		{
			ptr->setNext(ptr+1);
			ptr++;
		}
		
		ptr->setNext(0);
		
		//m_triChunkList = m_triPtr;
	}
	
	TriangleList *MemoryPool::newTriListEntry()
	{
		TriangleList *entry;
		entry = m_triListPtr;
		m_triListPtr = m_triListPtr->getNext();
		entry->setTrianglePtr(NULL);
		entry->setNext(NULL);
		
		return entry;
	}
	
	void MemoryPool::freeTriListEntry(TriangleList *entry)
	{
		TriangleList *triList = entry;
		while (triList) 
			triList = triList->getNext();
			
		triList->setNext(m_triListPtr);
		m_triListPtr = entry;
	}
	
	KDTreeNode *MemoryPool::newKDTreeNodePair()
	{
		unsigned long *longPtr = (unsigned long)m_kdNodePtr;
		longPtr[1] = longPtr[3] = 6;
		KDTreeNode *node = m_kdNodePtr;
		m_kdNodePtr += 2;
		
		return node;
	}

}